import { createApp } from 'vue'
import ViewUIPlus from 'view-ui-plus'
import App from './App.vue'
import router from './router'
import store from './store'
import 'view-ui-plus/dist/styles/viewuiplus.css'
import axios from 'axios'
import configs from '../config.js'
import VueClipboards from 'vue-clipboard2'

let server_address = configs.server || window.location.origin;
let baseURL = server_address + '/api';
let server_ip = baseURL.split('://')[1].split('/')[0].split(':')[0];
let server_port = baseURL.split('://')[1].split('/')[0].split(':')[1] || 80;

axios.defaults.baseURL = baseURL;

const app = createApp(App)

// 使用全局混入
app.mixin({
    beforeCreate() {
        // 在这里添加全局属性
        let that = this;
        let authErrorMessage = () => {
            if (!store.getters.isAuthMessageVisible) {
                store.commit('setAuthMessageVisible', true); // 设置消息可见状态
                that.$Message.error({
                    content: '登录已失效，请重新登录',
                    duration: 3,
                    onClose: () => {
                        store.commit('setAuthMessageVisible', false); // 消息关闭后重置状态
                    }
                });
              }
        }
        this.$http = {
            baseURL: baseURL,
            server_ip: server_ip,
            server_port: server_port,
            get(url) {
                return new Promise((resolve) => {
                    let token = localStorage.getItem('token')
                    axios.get(url, { 
                        headers: { Authorization: `Bearer ${token}` } 
                    }).then(res => {
                        resolve(res.data)
                    }).catch(err => {
                        if (err.response.status == 401 || err.response.status == 422) {
                            if(that.$route.path != '/login') {
                                authErrorMessage()
                                that.$router.push('/login')
                            }
                        }else {
                            console.log(err)
                        }
                    })
                })
            },
            post(url, data) {
                return new Promise((resolve) => {
                    let token = localStorage.getItem('token')
                    let headers = token ? { 'Authorization': `Bearer ${token}` } : {};
                    axios.post(url, data, {
                        headers: headers
                    }).then(res => {
                        resolve(res.data)
                    }).catch(err => {
                        if (err.response.status == 401 && err.response.status == 422) {
                            if(that.$route.path != '/login') {
                                authErrorMessage()
                                that.$router.push('/login')
                            }
                        }else {
                            console.log(err)
                        }
                    })
                })
            },
            downloadFile(filename) {
                const token = localStorage.getItem('token'); // 从登录状态获取
                let headers = token ? { 'Authorization': `Bearer ${token}` } : {};
                fetch(`${server_address}/${filename}`, {
                  method: 'GET',
                  headers: headers,
                })
                  .then(response => {
                    if (!response.ok) throw new Error('Failed to download file');
                    return response.blob();
                  })
                  .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    a.click();
                    window.URL.revokeObjectURL(url);
                  })
                  .catch(err => alert('Download failed: ' + err.message));
              },
        };
        this.errorMessage = (msg, duration = 5) => {
            if (typeof(msg) == 'string') {
                msg = {
                    content: msg,
                    duration: duration,
                    closable: true
                }
            }
            this.$Message.error(msg);
        };
    }
});


app.use(store)
    .use(router)
    .use(ViewUIPlus)
    .use(VueClipboards)
    .mount('#app')
